# -*- coding: UTF-8 -*-
import scrapy
import signal
from scrapy.selector import Selector

from scrapy.http import Request
import traceback
from scrapy import signals
import os, sys
from pangolin.common.date_common import DateCommon
from pangolin.spider_enum.companyCodeEnum import getCompanyCode
from pangolin.common.db_operateCommon import *
from pangolin.common.string_common import StringCommon
from pangolin.items import TicketDetailItem
from pangolin.common.http_common import *
import logging
import re
from urlparse import urljoin
from pangolin.settings import IS_SAVE_SERVER
from pangolin.settings import IS_SNAPSHOT
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from PIL import Image
from datetime import *
import time
import urllib

reload(sys)
sys.setdefaultencoding('UTF-8')


class PangolinSpider(scrapy.Spider):
    name = 'qnr_ticket_by_qnr_scenery_m_spider'
    allowed_domain = 'qunar.com'  # 允许爬虫运行的域

    # start_urls = [
    #     'http://www.ly.com/scenery/scenerysearchlist_2_41__0__0__0_0_0.html']

    def __init__(self, crawler, spider_name, city_code, company_code, task_id, task_date, timer_param,
                 timer_granularity, timer_id, url, lv_product_id, miss_product_flag):
        # 接受入参,全局引用
        self.save_server = IS_SAVE_SERVER
        self.snapshot = IS_SNAPSHOT

        self.spider_name = spider_name
        self.city_code = city_code
        self.company_code = company_code
        self.task_id = task_id
        self.task_date = task_date
        self.timer_param = timer_param
        self.timer_granularity = timer_granularity
        self.timer_id = timer_id
        self.url = url
        self.lv_product_id = lv_product_id
        self.miss_product_flag = miss_product_flag
        first_page_url = []
        lv_product_ids = {}
        # 根据cityCode获得城市名称，并且设置起始页以及下一页
        db_operate = DbOperateClass()
        if self.miss_product_flag == 'FALSE':
            sql = "SELECT qnr_name, city_name, product_id FROM cpa_care_product WHERE city_code = '" + city_code + "' AND business_code='TICKET'"
        else:
            sql = "SELECT qnr_name, city_name, product_id FROM cpa_care_product WHERE qnr_url LIKE '%" + url + "%' AND business_code='TICKET'"
            logging.info("%s_sql:%s" % (self.spider_name, sql))
        (fc, count) = db_operate.select_by_sql(sql)
        for row in fc:
            scenery_name = row[0]
            scenery_name = scenery_name.replace("（", " （").replace("(", "（").replace(")", "）")
            city_name = row[1]
            product_id = row[2]
            base_url = "http://touch.piao.qunar.com/touch/list_%E4%B8%8A%E6%B5%B7_sceneryName cityName.html?region=%E4%B8%8A%E6%B5%B7&isForeign=true&pageSize=20"
            scenery_url = base_url.replace("sceneryName", scenery_name).replace("cityName", city_name)
            keyword = scenery_name + " " + city_name
            lv_product_ids.setdefault(base_url.replace("sceneryName cityName", urllib.quote(str(keyword))), product_id)
            first_page_url.append(scenery_url)

        if self.miss_product_flag == 'FALSE':
            # 爬虫爬取前先删除同一批次同一城市的数据
            db_operate.delete_pd_and_cd_data("ticket_pdetail_qnr", "ticket_cdetail_qnr", getCompanyCode(company_code),
                city_code, task_id, task_date)

        self.base_urls = "http://touch.piao.qunar.com"
        self.lv_product_ids = lv_product_ids
        self.start_urls = first_page_url
        # 绑定爬虫开始和结束信号，便于监听爬虫开始与结束
        self.crawler = crawler
        cs = crawler.signals
        cs.connect(self.spider_closed, signals.spider_closed)
        cs.connect(self.spider_opened, signals.spider_opened)

    def parse(self, response):
        sel = Selector(response)
        try:
            product_tag = sel.css('.mp-view-list .mp-sight-group')
            lowest_price_tag = sel.css('.mp-sight-price > em::text')
            if product_tag and lowest_price_tag:
                for site in product_tag:
                    relative_url = site.css('.mp-sight-info > a').xpath('@href').extract()[0]
                    lowest_price = site.css('.mp-sight-price > em::text').extract()[0]
                    detail_url = urljoin(self.base_urls, relative_url)
                    lv_product_id = self.lv_product_ids.get(response.url)
                    request = Request(detail_url, meta={'lowest_price': lowest_price, 'lv_product_id': lv_product_id},
                                      callback=self.parse_product_list)
                    yield request
                    break
            else:
                logging.info("%s_无此产品或此产品已下架！！！" % self.spider_name)
                logging.info("页面源码：%s ,%s" % (response.url, response.body))
        except Exception as e:
            db_operate = DbOperateClass()
            logging.error("记录日志：标签变动 %s ,%s" % (response.url, e))
            logging.info("页面源码：%s ,%s" % (response.url, response.body))
            logging.error("qnr_ticket_by_scenery_m_spider_Exception: %s" % traceback.format_exc().replace("\"", "'"))

            # 错误描述只截取前500个字符，剩下的用***代替
            error_desc = traceback.format_exc().replace("\"", "'").replace(" ", "")
            if len(error_desc) > 500:
                error_desc = error_desc[:500] + '***'
            # 错误日志记入日志表
            sql = "insert into cpa_oper_log (log_type,company_code,busi_type,url,batch_num,timer_code,error_code,error_desc,task_id,task_date) values (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\" ,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")" \
                  % ("C", getCompanyCode(self.company_code), "门票", response.url, self.task_date, "timer_code",
                     "error_code", error_desc, str(self.task_id), str(self.task_date))
            db_operate.update_by_sql(sql)

    def parse_product_list(self, response):  # 页面解析函数，这里必须为parse()
        lowest_price = response.meta['lowest_price']
        lv_product_id = response.meta['lv_product_id']
        sels = Selector(response)
        try:
            item = TicketDetailItem()
            item['type'] = "TICKET"
            item['timer_param'] = self.timer_param
            item['timer_granularity'] = self.timer_granularity
            item['business_type'] = "ticket"

            item['product_table'] = "ticket_pdetail_qnr"
            item['data_type'] = "TicketDetail"
            item['detail_id'] = DateCommon.get_id_by_datetime()
            item['company_code'] = getCompanyCode(self.company_code)
            item['platform_code'] = "WAP"  # 操作平台WAP，PC
            item['city_code'] = self.city_code
            item['scenery_name'] = StringCommon.remove_blank(
                sels.xpath('//*[@class="mp-headfeagure-title"]/text()').extract()[0]).replace("A", "") \
                .replace("景区", "").replace("(", "").replace(")", "")  # 景点名称
            item['scenery_addr'] = StringCommon.remove_blank(
                sels.xpath('//*[@class="mp-baseinfo-address-txt"]/text()').extract()[0])  # 景点地址
            item['detail_url'] = response.url  # 详情页链接
            item['product_id'] = item['detail_url'].split('detail_')[1].split('.html')[0]

            # 产品详情
            item['lowest_price'] = lowest_price
            item['score'] = sels.xpath('//*[@class="mp-comments-tagscore"]/text()').extract()[0]  # 评分
            item['image_num'] = sels.xpath('//*[@class="mp-imgswipeicon-number"]/text()').extract()[0]
            item['introduction'] = ""

            score_tag = StringCommon.remove_blank(
                sels.xpath('//*[@class="mp-iconfont mpf-starlevel-gain"]/text()').extract()[0])  # 评分标签，印象
            dr = re.compile(r'<[^>]+>', re.S)
            score_tag = dr.sub('', score_tag)
            item['score_tag'] = score_tag.replace("B", "☆")
            if item['scenery_name'].count("A") > 0:
                item['star_level'] = str(item['scenery_name'].count("A")) + "A"
            else:
                item['star_level'] = ""
            item['create_time'] = DateCommon.get_current_date()
            item['update_time'] = item['create_time']
            item['task_id'] = self.task_id
            item['task_date'] = self.task_date
            item['lv_product_id'] = lv_product_id
            if self.snapshot == 'TRUE':
                # 获得截图地址
                compress_path = self.save_screenshot(response, item['product_id'], self.city_code,
                                                     self.company_code, self.task_id, self.task_date)
                item['snapshot_addr'] = compress_path
            else:
                item['snapshot_addr'] = " "
            # 商品详情
            item['commodity_table'] = "ticket_cdetail_qnr"
            item['commodity_type'] = []  # 商品类型或名称
            item['commodity_id'] = []  # 商品id
            item['commodity_name'] = []  # 商品名称
            item['commodity_url'] = []  # 商品名称
            item['sale_cond'] = []  # 提前时间、销售条件
            item['refund_cond'] = []  # 退改条件
            item['rack_rate'] = []  # 门市价
            item['sale_price'] = []  # 售价
            item['preferential'] = []  # 优惠
            item['price_list_id'] = ""
            product_tag = sels.css('.mp-ticket-container')
            if product_tag:
                sites_evens = sels.css('.mp-ticket-container .mp-ticket-group')
                for i, sites in enumerate(sites_evens):
                    commodity_type = sites.css('.mp-ticket-type.mp-border-bottom').xpath('text()').extract()[0]
                    child_site = sites.css('.mp-ticket-group .mp-ticket-list')
                    for child_sites in child_site:
                        commodity_id = child_sites.css('.mp-ticket-list').xpath('@data-typeid').extract()[0]
                        sale_price = StringCommon.remove_blank(
                            child_sites.css('.mp-ticket-type-price > em').xpath('text()').extract()[0])
                        sale_cond = []
                        refund_cond = []
                        rack_rate = []
                        commodity_name = []
                        preferential = []
                        commodity_url = []
                        commodity_list_tag = sites.css('.mp-ticket-default .mp-ticket-item')
                        if commodity_list_tag:
                            for commodity in commodity_list_tag:
                                commodity_tag = commodity.css('.mp-ticket-onedaytitle')
                                # if commodity_type == '一日游':  # 判断是否是一日游，处理标签方式不一样
                                if commodity_tag:
                                    commodity_name1 = StringCommon.remove_blank(
                                        commodity.css('.mp-ticket-onedaytitle').xpath('text()').extract()[0])
                                    rack_rate1 = ""
                                    refund_cond1 = ""
                                    sale_cond1 = StringCommon.remove_blank(
                                        commodity.css('.mp-ticket-onedaymore > span:nth-child(1)').xpath(
                                            'text()').extract()[
                                            0])
                                else:
                                    commodity_name1_tag = commodity.css('.mp-ticket-title').xpath('text()')
                                    commodity_name1 = commodity_name1_tag.extract()[0] if commodity_name1_tag else ""
                                    # commodity_name1 = StringCommon.remove_blank(
                                    #     commodity.css('.mp-ticket-title').xpath('text()').extract()[0])
                                    rack_rate1_tag = commodity.css('.mp-ticket-cost > em')
                                    if rack_rate1_tag:
                                        rack_rate1 = StringCommon.remove_blank(
                                            commodity.css('.mp-ticket-cost > em').xpath('text()').extract()[0])
                                    else:
                                        rack_rate1 = ""
                                    refund_cond1 = StringCommon.remove_blank(
                                        commodity.css('.mp-ticket-light > span:nth-child(2)').xpath('text()').extract()[
                                            0])
                                    sale_cond1 = StringCommon.remove_blank(
                                        commodity.css('.mp-ticket-light > span:nth-child(1)').xpath('text()').extract()[
                                            0])

                                sale_price1 = StringCommon.remove_blank(
                                    commodity.css('.mp-ticket-sale > em').xpath('text()').extract()[0])

                                commodity_url_tag = commodity.css('.mp-ticket-side > a').xpath('@href').extract()[0]
                                commodity_url1 = urljoin(self.base_urls, commodity_url_tag)
                                preferential_tag = commodity.css('.mp-ticket-redpacket')
                                if preferential_tag:
                                    preferential_tag = StringCommon.remove_blank(
                                        commodity.css('.mp-ticket-redpacket').extract()[0])  # 优惠
                                    dr = re.compile(r'<[^>]+>', re.S)
                                    preferential1 = dr.sub('', preferential_tag)
                                else:
                                    preferential1 = ""
                                # 找到低价供应商商品重置数组，跳出循环；否则继续遍历供应商商品
                                if sale_price == sale_price1:
                                    sale_cond = [sale_cond1]
                                    refund_cond = [refund_cond1]
                                    rack_rate = [rack_rate1]
                                    commodity_name = [commodity_name1]
                                    preferential = [preferential1]
                                    commodity_url = [commodity_url1]
                                    break
                                else:
                                    sale_cond.append(sale_cond1)
                                    refund_cond.append(refund_cond1)
                                    rack_rate.append(rack_rate1)
                                    commodity_name.append(commodity_name1)
                                    preferential.append(preferential1)
                                    commodity_url.append(commodity_url1)
                        else:
                            commodity_name1 = StringCommon.remove_blank(
                                child_site.css('.mp-ticket-type-name ').xpath('text()').extract()[0])
                            rack_rate1 = ""
                            refund_cond1 = ""
                            sale_cond1 = ""
                            preferential1 = ""
                            commodity_url_tag = child_site.css('.mp-ticket-list > a').xpath('@href').extract()[0]
                            commodity_url1 = urljoin(self.base_urls, commodity_url_tag)
                            sale_cond.append(sale_cond1)
                            refund_cond.append(refund_cond1)
                            rack_rate.append(rack_rate1)
                            commodity_name.append(commodity_name1)
                            preferential.append(preferential1)
                            commodity_url.append(commodity_url1)

                        item['commodity_type'].append(commodity_type)  # 商品类型或名称
                        item['commodity_id'].append(commodity_id)  # 商品id
                        # 以下字段均取数组第一条记录
                        item['commodity_name'].append(commodity_name[0])  # 商品名称
                        item['commodity_url'].append(commodity_url[0])  # 商品链接
                        item['sale_cond'].append(sale_cond[0])  # 提前时间、销售条件
                        item['refund_cond'].append(refund_cond[0])  # 退改条件
                        item['rack_rate'].append(rack_rate[0])  # 门市价
                        item['sale_price'].append(sale_price)  # 售价
                        item['preferential'].append(preferential[0])  # 优惠
                yield item
            else:
                yield item
        except Exception as e:
            db_operate = DbOperateClass()
            logging.info("记录日志：标签变动 %s ,%s" % (response.url, e))
            logging.info("页面源码：%s ,%s" % (response.url, response.body))
            logging.error("qnr_ticket_by_scenery_m_spider_Exception: %s" % traceback.format_exc().replace("\"", "'"))
            # 错误描述只截取前500个字符，剩下的用***代替
            error_desc = traceback.format_exc().replace("\"", "'").replace(" ", "")
            if len(error_desc) > 500:
                error_desc = error_desc[:500] + '***'
            # 错误日志记入日志表
            sql = "insert into cpa_oper_log (log_type,company_code,busi_type,url,batch_num,timer_code,error_code,error_desc,task_id,task_date) values (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\" ,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")" \
                  % ("C", getCompanyCode(self.company_code), "门票", response.url, self.task_date, "timer_code",
                     "error_code", error_desc, str(self.task_id), str(self.task_date))
            db_operate.update_by_sql(sql)


        # 按元素截图
    def save_screenshot(self, response, product_id, city_code, company_code, task_id, task_date):
        compress_path = ""
        try:
            file_name = getCompanyCode(
                company_code) + "__" + city_code + "__" + task_id + "__" + task_date + "__" + product_id + ".png"
            service_args = [
                '--proxy=' + response.meta['proxy'],
                '--load-images=no', ]
            dcap = dict(DesiredCapabilities.PHANTOMJS)
            # # 伪造ua信息
            # dcap["phantomjs.page.settings.userAgent"] = (request.headers['User-Agent'])
            dcap["phantomjs.page.settings.resourceTimeout"] = 5000  # 超时
            # 添加头文件
            dcap["phantomjs.page.customHeaders.Referer"] = (response.url)
            driver = webdriver.PhantomJS(desired_capabilities=dcap, service_args=service_args)  # 线上使用方式
            logging.info("%s PhantomJS is getUrl..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            driver.set_page_load_timeout(100)
            driver.set_script_timeout(100)
            driver.get(response.url)

            # 截图
            path = os.getcwd() + "/screenshot/" + file_name
            logging.info("%s save_screenshot is starting..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            driver.save_screenshot(path)
            logging.info("%s save_screenshot is end..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

            # 根据元素获得裁剪区域的坐标
            element = driver.find_element_by_xpath("//*[@id='main-page']/div[2]/div[2]")
            element1 = driver.find_element_by_xpath(
                "//*[@id='list-container']/div[1]")  # //*[@class='mp-ticket-container']
            left = int(element.location['x'])
            top = int(element.location['y'])
            right = int(element.location['x'] + element.size['width'])
            bottom = int(60 + element.location['y'] + element.size['height'] + element1.size['height'])
            # 根据获得的裁剪区域坐标截图
            compress_path = os.getcwd() + "/compressImage/" + file_name
            im = Image.open(path)
            im = im.crop((left, top, right, bottom))  # (left, top, right, bottom)
            im.save(compress_path)
            os.remove(path)
        except Exception as e:
            logging.error("截图失败 %s ,%s" % (response.url, e))
        finally:
            try:
                driver.service.process.send_signal(signal.SIGTERM)
                driver.quit()
            except Exception as e:
                logging.error("driver.quit_failed %s" % e)
        return compress_path

    @classmethod
    def from_crawler(cls, crawler, **kwargs):
        logging.info('inside_from_crawler: ')

        if kwargs['miss_product_flag'] == 'FALSE':
            kwargs['url'] = ''
            kwargs['lv_product_id'] = ''
        else:
            kwargs['timer_granularity'] = ''
            kwargs['timer_id'] = ''

        return cls(
            crawler,
            spider_name=kwargs['spider_name'],
            city_code=kwargs['city_code'],
            company_code=kwargs['company_code'],
            task_id=kwargs['task_id'],
            task_date=kwargs['task_date'],
            timer_param=kwargs['timer_param'],
            timer_granularity=kwargs['timer_granularity'],
            timer_id=kwargs['timer_id'],
            url=kwargs['url'],
            lv_product_id=kwargs['lv_product_id'],
            miss_product_flag=kwargs['miss_product_flag']
        )

    def spider_opened(self, spider):
        logging.info('Spider_opened_list: %s' % spider.name)
        # 爬虫设为启动状态2
        if self.miss_product_flag == 'FALSE':
            db_operate = DbOperateClass()
            db_operate.update_status(2, "PYTHON", self.timer_id)

    def spider_closed(self, spider, reason):
        logging.info('spider_closed_list: %s ,reason:%s' % (spider.name, reason))
        db_operate = DbOperateClass()

        if self.miss_product_flag == 'TRUE':  # 补录
            db_operate.update_miss_status(1, self.url, self.task_id)
        else:
            sql = "SELECT timer.timer_status FROM cpa_timer timer WHERE timer.timer_type='PYTHON' AND timer.timer_id = '" \
                + self.timer_id + "'"
            (fc, count) = db_operate.select_by_sql(sql)
            spider.logger.info('SELECT_COUNT: %s ,SQL:%s' % (count, sql))
            timer_status = ""
            for row in fc:
                timer_status = row[0]
            logging.info("timer_status:%s" % timer_status)
            if timer_status == '2':
                db_operate.update_status(5, "PYTHON", self.timer_id)
